629. K Inverse Pairs Array
629. K Inverse Pairs Array
Description
Solution
The tricky point is how to get the recurrence relation. We could ituitively give dp[i][j]
as for i length array, the number of k’s inverse pairs. Then let’s figure out the recurrence relation
Assume we already have dp[n][k]
, then we add one item afterwards. We have
1 | [1 2 3 4 5] 6 |
We can insert 6 into 6 slot to get more 5,4,3,2,1,0
more inverse pairs.
so dp[n][k] = dp[n-1][k] + dp[n-1][k-1] + ... + dp[n-1][k - (n-1)]
Then we could use dp[n][k-1] = dp[n-1]][k-1] + dp[n-1][k-2] + ... + dp[n-1][k-1 - (n-1)]
to replace some terms in previous formula.
dp[n][k] = dp[n-1][k] + dp[n][k-1] - dp[n-1][k-n]
Code
1 | class Solution { |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.